package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.constants.article.ArticleConstants;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    GeneratePageService generatePageService;

    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 查询 并 校验自媒体文章
        WmNews wmNews = getWmNews(newsId);
        // 2. 封装成apArticle
        ApArticle article = getApArticle(wmNews);
        // 3. 保存或修改  apArticle文章信息
        saveOrUpdateArticle(article);
        // 4. 保存 配置 config  和 内容 content 表信息
        saveConfigAndContent(article,wmNews);
        // 5. TODO 页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),article);
        // 6. 更新 wmNews状态
        updateWmNews(wmNews,article);
        // 7. TODO 通知es索引库新增文章索引
    }

    @Value("${file.oss.web-site}")
    String webSite;

    @Value("${file.minio.readPath}")
    String readPath;

    @Autowired
    ApArticleMapper apArticleMapper;

    /**
     * 根据参数加载文章列表
     * @param loadtypeLoadMore
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtypeLoadMore, ArticleHomeDTO dto) {
        Integer size = dto.getSize();
        if (size==null || size<=0) {
            size=10;
        }
        if (dto.getTag()==null) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMaxBehotTime()==null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime()==null) {
            dto.setMinBehotTime(new Date());
        }
        if (!loadtypeLoadMore.equals(ArticleConstants.LOADTYPE_LOAD_MORE)  && !loadtypeLoadMore.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtypeLoadMore=ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto,loadtypeLoadMore);
        for (ApArticle apArticle : apArticleList) {
            String images = apArticle.getImages();
            if (StringUtils.isNotBlank(images)) {
                images = Arrays.stream(images.split(","))
                        .map(url -> (webSite + url))
                        .collect(Collectors.joining(","));
                apArticle.setImages(images);
            }
            apArticle.setStaticUrl(readPath+ apArticle.getStaticUrl());
        }
        return ResponseResult.okResult(apArticleList);
    }

    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
        if (firstPage) {
            String hotArticleJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNoneBlank(hotArticleJson)) {
                List<HotArticleVo> hotArticleVos = JSON.parseArray(hotArticleJson, HotArticleVo.class);
                for (HotArticleVo hotArticleVo : hotArticleVos) {
                    String images = hotArticleVo.getImages();
                    if (StringUtils.isNoneBlank(images)) {
                        images = Arrays.stream(images.split(",")).map(image -> webSite+image).collect(Collectors.joining(","));
                    }
                    hotArticleVo.setStaticUrl(readPath+hotArticleVo.getStaticUrl());
                }
                return ResponseResult.okResult(hotArticleVos);
            }
        }
        return load(loadtypeLoadMore,dto);
    }

    @Autowired
    WemediaFeign wemediaFeign;
    /**
     * 更新 wmNews状态
     * @param wmNews
     * @param article
     */
    private void updateWmNews(WmNews wmNews, ApArticle article) {
        wmNews.setArticleId(article.getId());
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        ResponseResult<WmNews> result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            log.error("文章发布失败 运程调用自媒体修改状态失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }

    /**
     * 保存 配置 config  和 内容 content 表信息
     * @param article
     * @param wmNews
     */
    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(article.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        apArticleConfigMapper.insert(apArticleConfig);
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(wmNews.getContent());
        apArticleContent.setArticleId(article.getId());
        apArticleContentMapper.insert(apArticleContent);
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    /**
     * 保存或修改  apArticle文章信息
     * @param article
     */
    private void saveOrUpdateArticle(ApArticle article) {
        if (article.getId()==null) {
            article.setCollection(0);
            article.setComment(0);
            article.setLikes(0);
            article.setViews(0);
            save(article);
        }else {
            ApArticle byId = getById(article.getId());
            if (byId==null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            updateById(article);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId,article.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId,article.getId()));
        }
    }

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    private AuthorMapper authorMapper;

    /**
     * 封装成apArticle
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews,apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte) 0);
        apArticle.setLayout(wmNews.getType());
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            log.error("文章发布失败 远程调用admin频道接口失败  频道id:{}",wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        AdChannel channel = channelResult.getData();
        if (channel == null) {
            log.error("文章发布失败 频道不存在  频道id:{}",wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        apArticle.setChannelName(channel.getName());
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId,wmNews.getUserId()));
        if (apAuthor == null) {
            log.error("文章发布失败 关联的作者信息不存在");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        apArticle.setAuthorName(apAuthor.getName());
        return apArticle;
    }


    /**
     * 查询 并 校验自媒体文章
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        if (newsId==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ResponseResult<WmNews> wmNewsResult = wemediaFeign.findWmNewsById(newsId);
        if (!wmNewsResult.checkCode()) {
            log.error("文章发布失败 远程调用自媒体文章接口失败  文章id:{}",newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = wmNewsResult.getData();
        System.out.println("wmNews = " + wmNews);
        if (wmNews==null) {
            log.error("文章发布失败 远程调用自媒体文章接口失败  文章id:{}",newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"没有该文章");
        }
        short status = wmNews.getStatus();
        if (status != WmNews.Status.ADMIN_SUCCESS.getCode() && status != WmNews.Status.SUCCESS.getCode()) {
            log.error("文章发布失败 自媒体文章状态错误  文章id: {}   文章状态:{}",newsId,wmNews.getStatus());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章状态 不为 4或8  无法发布");
        }

        return wmNews;
    }
}
